<template>
  <div class="container">
    <div class="top">
      <div>
        <span>
          <span>区段：&nbsp;&nbsp;</span>
          <el-tree-select v-model="searchData.sectionId" :data="dataSource"
            :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" :render-after-expand="false"
            check-strictly @change="treeChange">
          </el-tree-select>
        </span>
        &nbsp;&nbsp;&nbsp;&nbsp;
        <span>
          <span>工区：&nbsp;&nbsp;</span>
          <el-tree-select v-model="searchData.workAreaId" :data="dataSourceArea"
            :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" :render-after-expand="false"
            check-strictly>
          </el-tree-select>
        </span>&nbsp;&nbsp;&nbsp;&nbsp;
        <el-button type="primary" plain @click="search">查询</el-button>
        <el-button type="primary" plain @click="resetSearch">重置</el-button>
      </div>
      <div>
        <el-button type="primary" @click="handleImport">导入</el-button>
        <el-button type="primary" @click="handleExport">导出</el-button>
        <el-button type="primary" @click="add">新增</el-button>
      </div>
    </div>

    <el-table :data="tableData" style="width: 100%" v-loading="loading" height="calc(100% - 20px)">
      <el-table-column type="index" label="序号" width="55"> </el-table-column>
      <el-table-column prop="section" label="区段"> </el-table-column>
      <el-table-column prop="workArea" label="工区"> </el-table-column>
      <el-table-column prop="location" label="问题地点"> </el-table-column>
      <el-table-column prop="device" label="设备名称"> </el-table-column>
      <el-table-column prop="leftRight" label="左右侧"> </el-table-column>
      <el-table-column prop="problem" label="存在问题描述"> </el-table-column>
      <el-table-column prop="signName" label="设置标志名称"> </el-table-column>
      <el-table-column prop="signLocation" label="设置标志地点"> </el-table-column>
      <el-table-column prop="signLeftRight" label="设置标志左右侧"> </el-table-column>
      <el-table-column prop="reason" label="设置原因"> </el-table-column>
      <el-table-column prop="remark" label="备注"> </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-icon title="编辑" @click="edit(scope.row)">
            <Edit />
          </el-icon>
          &nbsp;
          <el-icon title="删除" @click="del(scope.row)">
            <Delete />
          </el-icon>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增对话框 -->
    <el-dialog title="防洪警示标志详情" v-model="open" width="500px" append-to-body>
      <el-form ref="postRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="区段" prop="sectionId">
          <el-tree-select v-model="form.sectionId" :data="dataSource"
            :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" :render-after-expand="false"
            check-strictly @change="treeChange">
          </el-tree-select>
        </el-form-item>
        <el-form-item label="工区" prop="workAreaId">
          <el-tree-select v-model="form.workAreaId" :data="dataSourceArea"
            :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" :render-after-expand="false"
            check-strictly>
          </el-tree-select>
        </el-form-item>
        <el-form-item label="问题地点" prop="location">
          <el-input v-model="form.location" placeholder="请输入问题地点" />
        </el-form-item>
        <el-form-item label="设备名称" prop="device">
          <el-input v-model="form.device" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="左右侧" prop="leftRight">
          <el-select v-model="form.leftRight" clearable>
            <el-option label="左侧" value="左侧" />
            <el-option label="右侧" value="右侧" />
          </el-select>
        </el-form-item>
        <el-form-item label="存在问题描述" prop="problem">
          <el-input type="textarea" v-model="form.problem" placeholder="请输入存在问题描述" />
        </el-form-item>
        <el-form-item label="标志名称" prop="phone">
          <el-input v-model="form.signName" placeholder="请输入标志名称" />
        </el-form-item>
        <!-- <el-form-item label="位置" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入位置" />
        </el-form-item> -->
        <el-table :data="tableList" style="width: 100%" height="160px">
          <el-table-column prop="signLocation" label="设置标志地点">
            <template #default="scope">
              <el-input v-model="scope.row.signLocation" placeholder="请输入标志地点" />
            </template>
          </el-table-column>
          <el-table-column prop="signLeftRight" label="设置标志左右侧">
            <template #default="scope">
              <el-select v-model="scope.row.signLeftRight" clearable>
                <el-option label="左侧" value="左侧" />
                <el-option label="右侧" value="右侧" />
              </el-select>
            </template> </el-table-column>
          <el-table-column prop="date" label="操作">
            <template #default="scope">
              <el-icon title="新增" @click="addList(scope.row,scope.$index)">
                <Plus />
              </el-icon>
              &nbsp;
              <el-icon title="删除" @click="delList(scope.row,scope.$index)">
                <Delete />
              </el-icon>
            </template> </el-table-column>
        </el-table>
        <el-form-item label="设置原因" prop="reason">
          <el-input v-model="form.reason" placeholder="请输入设置原因" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="form.remark" placeholder="请输入位置" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip"><el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据</div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import {
    ElMessage,
    ElMessageBox
  } from 'element-plus'
  import {
    getSign,
    delSign,
    addSign,
    editSign,
    getTreeList,
    getDeptBy
  } from "@/api/work";
  const {
    proxy
  } = getCurrentInstance();

  //区段数据
  const dataSource = ref([])
  const dataSourceArea = ref([])

  function getTree() {
    getTreeList().then(res => {
      dataSource.value = res.data
    })
  }
  getTree()

  function treeChange(id) {
    searchData.value.workAreaId = ''
    form.value.workAreaId = ''
    getDeptBy({
      parentId: id
    }).then(res => {
      dataSourceArea.value = res.data
    })
  }

  const open = ref(false)
  const tableList = ref([{}])

  function addList(row) {
    tableList.value.push({
      signLocation:'',
      signLeftRight:''
    })
  }

  function delList(row, index) {
    tableList.value.splice(index, 1)
  }


  const tableData = ref([])
  const loading = ref(true);
  const route = useRoute();
  function getList() {
    console.log(route)
    console.log(route.query)
    loading.value = true
    getSign({
      keysAreasId:route.query.keysAreasId
    }).then(res => {
      tableData.value = res.rows
      loading.value = false
    })
  }
  getList()

  const searchData = ref({
    sectionId: '',
    workAreaId: ''
  })

  function search() {
    getSign(searchData.value).then(res => {
      tableData.value = res.rows
    })
  }

  function resetSearch() {
    searchData.value = {
      sectionId: '',
      workAreaId: ''
    }
    getList()
  }

  function add() {
    open.value = true
    form.value = {}
    dataSourceArea.value = []
    tableList.value = [{}]
  }

  import { getToken } from '@/utils/auth'
  /*** 导入参数 */
  const upload = reactive({
      // 是否显示弹出层
      open: false,
      // 弹出层标题
      title: '',
      // 是否禁用上传
      isUploading: false,
      // 是否更新已经存在的用户数据
      updateSupport: 0,
      // 设置上传的请求头部
      headers: { Authorization: 'Bearer ' + getToken() },
      // 上传的地址
      url: import.meta.env.VITE_APP_BASE_API + '/sjgtw-emergency/warningSign/importData',
  })
  /** 导入按钮操作 */
  function handleImport() {
      upload.title = '导入'
      upload.open = true
  }
  /** 提交上传文件 */
function submitFileForm() {
    proxy.$refs['uploadRef'].submit()
}
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
    upload.isUploading = true
}
  /** 下载模板操作 */
  function importTemplate() {
      proxy.download('sjgtw-emergency/warningSign/downloadTemplate', {}, `template_${new Date().getTime()}.xlsx`)
  }
  /** 文件上传成功处理 */
  const handleFileSuccess = (response, file, fileList) => {
      upload.open = false
      upload.isUploading = false
      proxy.$refs['uploadRef'].handleRemove(file)
      if (response.code == 200) {
          proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', { dangerouslyUseHTMLString: true })
      } else {
          proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.data + '</div>', '导入失败', { dangerouslyUseHTMLString: true })
      }
      getList()
  }

  /** 导出按钮操作 */
  function handleExport() {
    proxy.download("sjgtw-emergency/warningSign/export", {
      ...queryParams.value, 
    }, `防洪警示标志管理${new Date().getTime()}.xlsx`);
  }

  function edit(row) {
    if(row.sectionId){
      getDeptBy({
        parentId: row.sectionId
      }).then(res => {
        dataSourceArea.value = res.data
      })
    }

    if(row.signLocation && row.signLeftRight){
      tableList.value = []
      let signLocation = row.signLocation.split(",")
      let signLeftRight = row.signLeftRight.split(",")
      for(let i = 0;i<signLocation.length-1;i++){
        let obj = {
          signLocation:signLocation[i],
          signLeftRight:signLeftRight[i]
        }
        tableList.value.push(obj)
      }
    }else{
      tableList.value = [{}]
    }
    form.value = row
    open.value = true
  }

  function del(data) {
    ElMessageBox.confirm(
        '确认删除吗？',
        'Warning', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
      .then(() => {
        delSign(data.id).then(res => {
          ElMessage({
            type: 'success',
            message: '已删除',
          })
          getList()
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
  }

  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      postCode: undefined,
      postName: undefined,
      phone: undefined
    },
    rules: {
      // phone: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }],
      // postName: [{ required: true, message: "岗位名称不能为空", trigger: "blur" }],
      // postCode: [{ required: true, message: "岗位编码不能为空", trigger: "blur" }],
      // postSort: [{ required: true, message: "岗位顺序不能为空", trigger: "blur" }],
    }
  });
  const {
    queryParams,
    form,
    rules
  } = toRefs(data);

  function cancel() {
    open.value = false
  }

  function submitForm() {
    form.value.signLocation = ''
    form.value.signLeftRight = ''
    let flag = false
    if(tableList.value.length){
      tableList.value.forEach(item=>{
        if(item.signLocation == "" || item.signLeftRight == ""){
          flag = true
        }
        form.value.signLocation += item.signLocation +","
        form.value.signLeftRight += item.signLeftRight +","
      })
    }
    if(flag) return ElMessage({
          type: 'error',
          message: '设置标志地点或设置标志左右侧不能为空',
        })
    proxy.$refs["postRef"].validate(valid => {
      if (valid) {
        if (form.value.id != undefined) {
          editSign(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList()
          });
        } else {
          form.value.keysAreasId = route.query.keysAreasId
          addSign(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList()
          });
        }
      }
    });
  }
</script>

<style lang='scss' scoped>
  .container {
    height: 100%;
    width: 100%;
    padding: 20px;
  }

  .top {
    height: 40px;
    line-height: 40px;
    display: flex;
    justify-content: space-between;
  }

  .end {
    justify-content: flex-end;
  }

  :deep(.el-table .el-table__cell) {
    text-align: center;
  }
  :deep(.el-table--border::before) {
    width: 0px;;
  }
  :deep(.el-table--border::after) {
    width: 0px;;
  }
</style>